package com.android.kotlincoroutinemvvmdemo.view
import android.content.Context
import android.graphics.Canvas
import android.graphics.CornerPathEffect
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import com.android.kotlincoroutinemvvmdemo.R

/*
* RegularPolygonView
* */
class RegularPolygonView @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null
) : BaseView(context, attributeSet) {

    private val mPaint by lazy {
        Paint().apply {
            isAntiAlias = true
            isDither = true
            strokeJoin = Paint.Join.ROUND
            //style = Paint.Style.STROKE
            //strokeWidth = context.resources.getDimension(R.dimen.dp_2)
            pathEffect = CornerPathEffect(context.resources.getDimension(R.dimen.dp_6))
            style = Paint.Style.FILL
            color = context.resources.getColor(R.color.color_0CE6CD)
        }
    }

    private val mPath by lazy {
        Path()
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        setBackgroundColor(context.resources.getColor(R.color.color_F3F3F3))
        canvas?.apply {
            val cx = mWidth.toFloat() / 2
            val cy = mHeight.toFloat() / 2
            translate(cx, cy)
            save()
            rotate(36F)
            mPath.apply {
                val baseLength = cx * 9 / 10
                val x0 = baseLength * Math.cos(Math.toRadians(360.0)).toFloat()
                val y0 = baseLength * Math.sin(Math.toRadians(360.0)).toFloat()
                moveTo(x0, y0)
                for (i in 0.until(EDGES)) {
                    val radius = Math.toRadians(360.0 / EDGES * (i + 1))
                    val x1 = baseLength * Math.cos(radius).toFloat()
                    val y1 = baseLength * Math.sin(radius).toFloat()
                    lineTo(x1, y1)
                }
                close()
            }
            drawPath(mPath, mPaint)
            restore()
        }
    }

    companion object {
        const val EDGES = 7
    }
}